package com.xcm.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xcm.cache.RedisCacheDao;
import com.xcm.config.CustomProperties;
import com.xcm.constant.BusinessConstant;
import com.xcm.constant.PageConstant;
import com.xcm.constant.ResponseConstant;
import com.xcm.exception.ControllerException;
import com.xcm.exception.ServiceException;
import com.xcm.model.JsonResponse;
import com.xcm.model.TbDeviceUpgrade;
import com.xcm.model.dto.ApkDeviceListDTO;
import com.xcm.model.dto.DeviceGroupListDTO;
import com.xcm.model.dto.DeviceModelDTO;
import com.xcm.model.vo.DeviceUpgradeListVO;
import com.xcm.model.vo.DeviceUpgradeVO;
import com.xcm.page.PageInfo;
import com.xcm.service.DeviceGroupService;
import com.xcm.service.DeviceInfoService;
import com.xcm.service.DeviceModelService;
import com.xcm.service.DeviceUpgradeService;
import com.xcm.util.GetUserUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/deviceUpgrade")
public class DeviceUpgradeController {
	private static Logger logger = LoggerFactory.getLogger(DeviceUpgradeController.class);
	@Autowired
	private DeviceUpgradeService deviceUpgradeService;
	@Autowired
	private DeviceModelService deviceModelService;
	@Autowired
	private DeviceInfoService deviceInfoService;
	@Autowired
	private DeviceGroupService deviceGroupService;
	@Autowired
	private RedisCacheDao redisCacheDao;
	@Autowired
	private CustomProperties customProperties;

	/**
	 * 跳转至新增apk界面
	 * @return
	 */
	@RequestMapping(value = "/goAddApk")
	public String goAddApk(Model model){
		List<DeviceModelDTO> deviceModelList = deviceModelService.listDeviceModels();
		model.addAttribute("deviceModelList", deviceModelList);
		return "apk_add";
	}

	/**
	 * 保存终端升级信息
	 */
	@ResponseBody
	@RequestMapping(value = "/saveApk")
	public Object saveApk(TbDeviceUpgrade deviceUpgrade, HttpServletRequest request) {
		//获取用户信息
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("DeviceUpgradeController save 保存终端升级信息失败：" + e.getMessage());
			return new JsonResponse(ResponseConstant.CODE_FAIL,"保存终端升级信息失败");
		}
		if(user == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL,"用户名为空，请联系管理员");
		}
		//验证参数
		if (deviceUpgrade == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		//验证参数
		if (StringUtils.isBlank(deviceUpgrade.getName()) || StringUtils.isBlank(deviceUpgrade.getModel())
				|| StringUtils.isBlank(deviceUpgrade.getSize())|| deviceUpgrade.getVersionCode() == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		try {
			deviceUpgradeService.saveDeviceUpgrade(deviceUpgrade, user, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceUpgradeController save 保存终端升级信息失败：" + e.getMessage());
			return new JsonResponse(ResponseConstant.CODE_FAIL,"保存终端升级信息失败");
		}
		return "";
	}

	/**
	 * 删除终端升级
	 */
	@ResponseBody
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Object delete(String deviceUpgradeIds, HttpServletRequest request) {
		//验证参数
		if (StringUtils.isBlank(deviceUpgradeIds)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		try {
			deviceUpgradeService.deleteDeviceUpgradeBatch(deviceUpgradeIds, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceUpgradeController delete 删除终端升级失败：" + e.getMessage());
			return new ControllerException("删除终端升级失败");
		}
		return "";
	}

	/**
	 * 强制升级
	 */
	@ResponseBody
	@RequestMapping(value = "/setForce")
	public Object setForce(Long deviceUpgradeId, Integer force, HttpServletRequest request) {
		//获取用户信息
		JSONObject user = null;
		try {
			user = GetUserUtils.getUser(request, redisCacheDao, customProperties);
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error("DeviceUpgradeController setForce 强制升级失败：" + e.getMessage());
			return new JsonResponse(ResponseConstant.CODE_FAIL,"强制升级失败");
		}
		if(user == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL,"用户名为空，请联系管理员");
		}
		if (deviceUpgradeId == null || force == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		try {
			deviceUpgradeService.updateActive(deviceUpgradeId, force, user, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceUpgradeController setForce 强制升级失败：" + e.getMessage());
			return new JsonResponse(ResponseConstant.CODE_FAIL,"强制升级失败");
		}
		return "";
	}

	/**
	 * 获取apk列表
	 */
	@RequestMapping(value = "/apkList")
	public String apkList(String model, Model modelView, Integer pageNum, Integer pageSize) {
		if (StringUtils.isBlank(model)) {
			modelView.addAttribute("model", "参数不能为空");
		}
		try {
			PageInfo<DeviceUpgradeListVO> pageInfo = deviceUpgradeService.listDeviceUpgradeByPage(model, pageNum, pageSize);
			modelView.addAttribute("apkList", pageInfo.getList());
			modelView.addAttribute("total", pageInfo.getTotal());
			modelView.addAttribute("pageNum", pageInfo.getPageNum());
			modelView.addAttribute("pageSize", pageInfo.getPageSize());
			modelView.addAttribute("model", model);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceUpgradeController apkList 获取apk列表失败：" + e.getMessage());
		}
		return "apk_list";
	}

	/**
	 * 终端列表页面通过ajax获取apk列表
	 * @param pageNum
	 * @param pageSize
	 * @param model 机型
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/apkListforAjax")
	public Object apkListforAjax(Integer pageNum, Integer pageSize, String model, Model modelView) {
		if (StringUtils.isBlank(model)) {
			modelView.addAttribute("model", "参数不能为空");
		}
		if (pageNum == null) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null) {
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		PageInfo<DeviceUpgradeListVO> pageInfo = deviceUpgradeService.listDeviceUpgradeByPage(model, pageNum, pageSize);
		modelView.addAttribute("apkList", pageInfo.getList());
		modelView.addAttribute("total", pageInfo.getTotal());
		modelView.addAttribute("pageNum", pageNum);
		modelView.addAttribute("pageSize", pageSize);
		return modelView;
	}

	@RequestMapping(value = "/setDeviceUpdateList")
	public Object setDeviceUpdateList(String deviceInfoId, String deviceModel, Model model) {
		model.addAttribute("deviceInfoId",deviceInfoId);
		model.addAttribute("deviceModel",deviceModel);
		return "setDeviceUpdate_list";
	}

	/**
	 *  跳转至升级APK
	 */
	@RequestMapping(value = "/goUpgradeApk")
	public String goUpgradeApk(Long deviceUpgradeId, Model model) {
		if (deviceUpgradeId == null) {
			logger.error("DeviceUpgradeController goUpgradeApk 参数deviceUpgradeId为空，请联系管理员" );
		}
		try {
			//机型
			List<DeviceModelDTO> deviceModelList = deviceModelService.listDeviceModels();
			model.addAttribute("deviceModelList", deviceModelList);
			DeviceUpgradeVO deviceUpgradeVO = deviceUpgradeService.getDeviceUpgradeByIdVo(deviceUpgradeId);
			model.addAttribute("deviceUpgrade", deviceUpgradeVO);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceUpgradeController goUpgradeApk 升级APK：" + e.getMessage());
		}
		return "apk_upgrade";
	}


	/**
	 * 升级APK
	 */
	@ResponseBody
	@RequestMapping(value = "/upgradeApk", method = RequestMethod.POST)
	public Object upgradeApk(TbDeviceUpgrade deviceUpgrade,  HttpServletRequest request) {
		Long deviceUpgradeId = deviceUpgrade.getDeviceUpgradeId();
		if (deviceUpgradeId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "升级ID为空，请联系管理员");
		}
		try {
			deviceUpgradeService.updateDeviceUpgrade(deviceUpgrade, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceUpgradeController upgradeApk升级APK：" + e.getMessage());
			return e;
		}
		return "";

	}
	/**
	 *  apk-终端列表信息
	 */
	@RequestMapping(value = "/apkDeviceList")
	public String apkDeviceList(Long deviceUpgradeId,String mipsVersion, Integer deviceStatus, String model, String province,String city, String area,
	                             String groupCode, Integer pageNum, Integer pageSize, Model modelView) {
		//放入model，用户数据回显
		modelView.addAttribute("deviceUpgradeId", deviceUpgradeId);
		modelView.addAttribute("mipsVersion", mipsVersion);
		modelView.addAttribute("deviceStatus", deviceStatus);
		modelView.addAttribute("model", model);
		modelView.addAttribute("province", province);
		modelView.addAttribute("city", city);
		modelView.addAttribute("area", area);
		modelView.addAttribute("groupCode", groupCode);
		//mips版本号 TODO 终端上报的版本是取得是versionName上报的，所有这里下拉选项也改成查询versionName
		List<String> versionNameList = deviceInfoService.listAllMipsVersionCode();
		modelView.addAttribute("versionCodeList", versionNameList);
		//在线状态
		Map<Object, Object> deviceStatusMap = Maps.newHashMap();
		deviceStatusMap.put(BusinessConstant.DEVICE_INFO_STATUS_ON_LINE, "在线");
		deviceStatusMap.put(BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE, "离线");
		modelView.addAttribute("deviceStatusMap", deviceStatusMap);
		//机型
		List<DeviceModelDTO> deviceModelList = deviceModelService.listDeviceModelsSelectedOfApk(deviceUpgradeId);
		modelView.addAttribute("deviceModelList", deviceModelList);
		//分组
		List<DeviceGroupListDTO> deviceGroupList = deviceGroupService.listAllDeviceGroup();
		modelView.addAttribute("deviceGroupList", deviceGroupList);
		//apk-终端信息
		PageInfo<ApkDeviceListDTO> pageInfo = deviceInfoService.listApkDeviceByPage(mipsVersion, deviceStatus, model, province, city, area, groupCode, pageNum, pageSize);
		modelView.addAttribute("apkDeviceList", pageInfo.getList());
		modelView.addAttribute("total", pageInfo.getTotal());
		modelView.addAttribute("pageNum", pageInfo.getPageNum());
		modelView.addAttribute("pageSize", pageInfo.getPageSize());
		//在线总数
		Long onlineCount = deviceInfoService.getApkDeviceOnlineCount(mipsVersion, model, province, city, area, groupCode);
		modelView.addAttribute("onlineCount", onlineCount);
		//离线总数
		Long offlineCount = deviceInfoService.getApkDeviceOfflineCount(mipsVersion, model, province, city, area, groupCode);
		modelView.addAttribute("offlineCount",offlineCount);
		return "apk_device_list";
	}

	/**
	 * 更新mips
	 */
	@ResponseBody
	@RequestMapping(value = "/updateMips")
	public Object updateMips(String deviceInfoIds, Long deviceUpgradeId, HttpServletRequest request) {
		if (StringUtils.isBlank(deviceInfoIds)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL,"请选择终端");
		}
		if (deviceUpgradeId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL,"升级ID为空，请联系管理员");
		}
		try {
			deviceInfoService.updateSoftwareUpgradeIdByDeviceInfoIds(deviceInfoIds, deviceUpgradeId, request);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("DeviceUpgradeController apkList 更新mips失败：" + e.getMessage());
			return new JsonResponse(ResponseConstant.CODE_FAIL,"更新mips失败");
		}
		return "";
	}
}
